<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/31
 * Time: 16:00
 */

namespace app\api\controller\android\v13;


use think\Cache;
use think\Controller;
use app\api\model\Authority;
use think\db;
use app\index\model\Jpush;
use think\Request;
use think\Exception;
use  app\api\model\OrderModel;

class Transfer extends Controller {
    
    protected $us;
    
    public function _initialize() {
        $model    = new Authority();
        $this->us = $model->check(1);
    }
    
    /*
      * 转派记录添加
      */
    public function record() {
        $data                 = \request()->post();
        $OrderUserId          = db('order')->join('order_setting', 'order_setting.order_id=order.order_id', 'left')->where(['order.order_id' => $data['order_id']])->find();
        $dispatch_config_chanel = db('dispatch_config_chanel', config('database.zong'))->where('chanel_id', $OrderUserId['channel_details'])->where('city_id', config('cityId'))->find();
        //店长是否开启接单权限
        if ($dispatch_config_chanel['receiving_permission'] == 2) {
            $dispatch_config_user_chanel = db('dispatch_config_user_chanel', config('database.zong'))->where('chanel_id', $OrderUserId['channel_details'])->where('user_id', $data['user_id'])->find();
            if (empty($dispatch_config_user_chanel)) {
                r_date(null, 300, '该渠道开启了接单权限要求，该店长未拥有该渠道的接单权限');
            }
        }
        //店长是否开启了专人专项
        if ($dispatch_config_chanel['dedicated_task'] == 1) {
            $dispatch_config_user = db('dispatch_config_user', config('database.zong'))->where('dedicated_task',1)->where('user_id', $data['user_id'])->find();
            if (empty($dispatch_config_user)) {
                r_date(null, 300, '该渠道开启了专人专项权限要求，该店长未拥有该渠道的专人专项权限');
            }
        }
        //店长是否已被纳入该渠道黑名单
        $dispatch_config_blacklist = db('dispatch_config_blacklist', config('database.zong'))->where('chanel_id', $OrderUserId['channel_details'])->where('dispatch_config_blacklist.city_id', config('cityId'))->where('user_id', $data['user_id'])->find();
        if (!empty($dispatch_config_blacklist)) {
            r_date(null, 300, '该店长已被纳入该渠道黑名单，不可接此订单');
        }
        $transfer_record_confirm = db('transfer_record_confirm')->where(['transfer_record_confirm.order_id' => $data['order_id']])->field('sum(if(confirm=0,1,0)) as zhuan,sum(if(confirm=1,1,0)) as cheng')->where('confirm', 0)->order('id desc')->select();
        $zhuan                   = empty($transfer_record_confirm[0]['zhuan']) ? 0 : $transfer_record_confirm[0]['zhuan'];
        $cheng                   = empty($transfer_record_confirm[0]['cheng']) ? 0 : $transfer_record_confirm[0]['cheng'];
        if ($zhuan > 0) {
            r_date(null, 300, '如果要重新转派，请在页面上方取消转派后，再进行操作');
        }
        if ($OrderUserId['order_resetuser_limit'] == 0) {
            r_date(null, 300, '可转派次数已用完，且接到转派的单无法再次转派（如需转派，请在企业微信里特殊申请）');
        }
        $order_transfer_record = db('order_transfer_record')->where(['order_transfer_record.order_id' => $data['order_id']])->order('id desc')->find();
        if (!empty($order_transfer_record) && $order_transfer_record['admin_id'] == $this->us['user_id'] && $this->us['reserve'] == 2) {
            r_date(null, 300, '该订单已经转派');
        }
        $reason = json_decode($data['selectJson'], true);
        if (empty($reason)) {
            r_date(null, 300, '请添加转派原因');
        }
        $reasonSelect = [];
        foreach ($reason as $o) {
            foreach ($o['select'] as $l) {
                $reasonSelect[] = $l['title'];
            }
            
        }
        \db('transfer_record_confirm')->insert(['user_id' => $data['user_id'], 'create_time' => time(), 'order_id' => $data['order_id'], 'operation' => $this->us['user_id'], 'reason' => implode(",", $reasonSelect), 'reason_json' => $data['selectJson']]);
        r_date(null, 200);
        
    }
    
    /*
     * 转派原因
     */
    public function reason() {
        $sys_config = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'order_transfer_reason')->value('valuess');
        $sys_config = json_decode($sys_config, true);
        r_date($sys_config, 200);
    }
    
    /*
     * 转派列表查询当前订单是否转派状态
     */
    public function transferInformation() {
        $data                    = Authority::param(['orderId']);
        $transfer_record_confirm = \db('transfer_record_confirm')->join('user', 'user.user_id=transfer_record_confirm.user_id', 'left')->field('transfer_record_confirm.user_id,transfer_record_confirm.role,FROM_UNIXTIME(transfer_record_confirm.create_time,"%Y-%m-%d %H:%i:%s") as time,if(transfer_record_confirm.confirm=0,"转派中","") as title,transfer_record_confirm.id,user.username')->where('order_id', $data['orderId'])->where('confirm', 0)->find();
        
        
        r_date($transfer_record_confirm, 200);
    }
    
    /*
    * 转派列表查询当前订单是确认
    */
    public function transferConfirmation(OrderModel $orderModel) {
        $transfer_record_confirm = \db('transfer_record_confirm')->join('user', 'user.user_id=transfer_record_confirm.operation', 'left')->join('order', 'order.order_id=transfer_record_confirm.order_id', 'left')->join('order_times', 'order_times.order_id=transfer_record_confirm.order_id', 'left')->join('order_info', 'order_info.order_id=transfer_record_confirm.order_id', 'left')->field('user.username,FROM_UNIXTIME(transfer_record_confirm.create_time,"%Y-%m-%d %H:%i:%s") as time,order_times.dispatch_time as dispatchTime,order_info.pro_id_title as sku,order_info.pro_id1_title as sku1,concat(order_info.city,order_info.county,order.addres) as addres,order.state,order.undetermined,order_times.envelopes_time as envelopesTime,order_times.signing_time as contractConTime,order_times.late_through_time as lateThTime,order_times.late_clock_time as lateClockTime,envelopes_first_time as envelopesFirstTime,order_times.first_clock_time as firstClockTime,transfer_record_confirm.id,transfer_record_confirm.order_id,order.planned')->where('transfer_record_confirm.user_id', $this->us['user_id'])->where('confirm', 0)->find();
        $list                    = null;
        if (!empty($transfer_record_confirm)) {
            $transfer_record_confirm['tai'] = 0;
            $title                          = $orderModel->judge($transfer_record_confirm);
            $list['stateTitle']             = $title['stateTitle'];
            $list['username']               = "你好，" . $transfer_record_confirm['username'] . "将订单转派给你，请及时确认是否接单，接单后，订单将无法转派";
            $list['time']                   = $transfer_record_confirm['time'];
            $list['dispatchTime']           = date('Y-m-d H:i:s', $transfer_record_confirm['dispatchTime']);
            $list['sku']                    = $transfer_record_confirm['sku'];
            $list['sku1']                   = $transfer_record_confirm['sku1'];
            $list['orderId']                = $transfer_record_confirm['order_id'];
            $list['addres']                 = $transfer_record_confirm['addres'];
            $list['id']                     = $transfer_record_confirm['id'];
        }
        
        r_date($list, 200);
    }
    
    /*
    * 转派列表查询当前订单是确认
    */
    public function transferConfirmationSubmit(Jpush $jpush) {
        $data = Authority::param(['id', 'state', 'orderId']);
        db()->startTrans();
        try {
            \db('transfer_record_confirm')->where('id', $data['id'])->update(['confirm_time' => time(), 'confirm' => $data['state'], 'confirm_user_id' => $this->us['user_id']]);
            $data['order_id'] = $data['orderId'];
            if ($data['state'] == 1) {
                $transfer_record_confirm = \db('transfer_record_confirm')->where('id', $data['id'])->find();
                $user        = db('user')->where('user_id', $transfer_record_confirm['user_id'])->find();
                $OrderUserId             = db('order')->where(['order.order_id' => $data['order_id']])->find();
                $business_type=$OrderUserId['business_type'];
                $envelopes             = db('envelopes')->where(['envelopes.ordesr_id' => $data['order_id'],'delete_time'=>0])->count();
                if($envelopes>0 && $business_type !=$user['in_business']){
                   throw new Exception( '当前订单无法接单，【小改/大改/局改】店长已经有过报价，请拒绝接单。若仍然需要接单，需要原店长操作取消并退单至客服后，客服重新指派'); 
                }
                $business_type=$user['in_business'];
                $dispatch_config_chanel = db('dispatch_config_chanel', config('database.zong'))->where('city_id', config('cityId'))->where('chanel_id', $OrderUserId['channel_details'])->find();
                
                if ($OrderUserId['pro_id'] == 1) {
                    $value = 'wall_renovation_level';
                } elseif ($OrderUserId['pro_id'] == 3) {
                    $value = 'partial_renovation_level';
                } elseif ($OrderUserId['pro_id'] == 42) {
                    $value = 'waterproof_repair_level';
                } elseif ($OrderUserId['pro_id'] == 104) {
                    $value = 'maintenance_installation_level';
                } else {
                    $value = 'miscellaneous_level';
                }
                $dispatch_config_user = db('dispatch_config_user', config('database.zong'))->where('user_id', $transfer_record_confirm['user_id'])->find();
                
                if ($dispatch_config_user['available_dispatch_quantity'] < 1) {
                    throw new Exception( '因为您本月的接单额度已用完，所以无法接单。如果必须接单，只能将本月接单的商机转给他人，他人确认后，您才能恢复额度');
                }
                if ($dispatch_config_chanel['receiving_permission'] == 2) {
                    $dispatch_config_user_chanel = db('dispatch_config_user_chanel', config('database.zong'))->where('chanel_id', $OrderUserId['channel_details'])->where('user_id', $transfer_record_confirm['user_id'])->find();
                    if (empty($dispatch_config_user_chanel)) {
                        throw new Exception('该渠道开启了接单权限要求，该店长未拥有该渠道的接单权限');
                    }
                }
                //店长是否开启了专人专项
                if ($dispatch_config_chanel['dedicated_task'] == 1) {
                    $dispatch_config_user = db('dispatch_config_user', config('database.zong'))->where('dedicated_task',1)->where('user_id', $transfer_record_confirm['user_id'])->find();
                    if (empty($dispatch_config_user)) {
                        throw new Exception('该渠道开启了专人专项权限要求，该店长未拥有该渠道的专人专项权限');
                    }
                }
                $dispatch_config_blacklist = db('dispatch_config_blacklist', config('database.zong'))->where('chanel_id', $OrderUserId['channel_details'])->where('dispatch_config_blacklist.city_id', config('cityId'))->where('user_id', $transfer_record_confirm['user_id'])->find();
                if (!empty($dispatch_config_blacklist)) {
                    throw new Exception( '该店长已被纳入该渠道黑名单，不可接此订单');
                }
                $time = time();
                if ($transfer_record_confirm['confirm'] != 3) {
                    $op = \db('transfer_record')->insertGetId(['user_id' => $transfer_record_confirm['user_id'], 'time' => $time, 'order_id' => $transfer_record_confirm['order_id'], 'operation' => $transfer_record_confirm['operation'],]);
                }
                if ($transfer_record_confirm['role'] == 1) {
                    $admin_name = db('user')->where('user_id', $transfer_record_confirm['operation'])->value('username');
                    $admin_name = '店长-' . $admin_name;
                    $admin_role = 2;
                } elseif ($transfer_record_confirm['role'] == 2) {
                    $admin_name = db('admin', config('database.zong'))->where('admin_id', $transfer_record_confirm['operation'])->value('username');
                    $admin_role = 1;
                    $admin_name = '客服-' . $admin_name;
                }
                $types       = 1;
                
                $store_id    = $user['store_id'];
                $business_id = db('business_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $store_id])->where('status', 1)->value('business_id');

                \db('order_transfer_record')->insertGetId(['order_id' => $data['order_id'], 'original_user_id' => $OrderUserId['assignor'], 'transfer_user_id' => $transfer_record_confirm['user_id'], 'transfer_business_id' => empty($business_id) ? 0 : $business_id, 'transfer_store_id' => $store_id, 'types' => $types, 'admin_role' => $admin_role, 'order_aggregate' => json_encode(db('order_aggregate')->where(['order_id' => $transfer_record_confirm['order_id']])->find()), 'order_info' => json_encode(db('order_info')->where(['order_id' => $transfer_record_confirm['order_id']])->find()), 'admin_id' => $transfer_record_confirm['operation'], 'admin_name' => $admin_name, 'create_time' => $time, 'reason_json' => empty($transfer_record_confirm['reason_json']) ? '' : $transfer_record_confirm['reason_json'], 'reason' => empty($transfer_record_confirm['reason_json']) ? '' : $transfer_record_confirm['reason'],]);
                if ($op) {
                     $order_resetuser_limit=db('order_setting')->where(['order_id' => $data['order_id']])->value('order_resetuser_limit');
                     if($order_resetuser_limit<=0){
                          throw new Exception( '可转派次数已用完，且接到转派的单无法再次转派（如需转派，请在企业微信里特殊申请）');
                     }
                    $company_id = db('company_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $store_id])->where('status', 1)->value('company_id');
                    \db('order')->where('order_id', $data['order_id'])->update(['assignor' => $transfer_record_confirm['user_id'], 'company_id' => $company_id, 'store_id' => $store_id, 'business_id' => empty($business_id) ? 0 : $business_id,'business_type'=>$business_type]);
                    db('message')->where(['order_id' => $data['order_id']])->update(['already' => 0, 'have' => $time]);
                    db('remind')->where(['order_id' => $data['order_id']])->update(['tai' => 0]);
                    db('order_setting')->where(['order_id' => $data['order_id']])->setDec('order_resetuser_limit');
                    db('dispatch_config_user', config('database.zong'))->where(['user_id' => $transfer_record_confirm['user_id']])->update(['available_dispatch_quantity' => ['dec', 1], 'dispatch_quantity_used' => ['inc', 1]]);
                    db('dispatch_config_user', config('database.zong'))->where(['user_id' => $OrderUserId['assignor']])->update(['dispatch_quantity_used' => ['dec', 1]]);
                    $pai = db('dispatch_config_user', config('database.zong'))->where(['user_id' => $transfer_record_confirm['user_id']])->value('available_dispatch_quantity');
                    \db('user_dispatch_log', config('database.zong'))->insertGetId(['order_id' => $data['order_id'], 'user_id' => $transfer_record_confirm['user_id'], 'action_type' => 2, 'add_type' => 4, 'action_quantity' => 1, 'dispatch_quantity' => $pai, 'remark' => 'APP订单转派额度减少', 'create_time' => $time]);
                    $month = monthBetween();
                    $li    = db('order')->field('order.*,st.store_id,st.store_name,us.*,p.province,c.city,y.county,order_times.dispatch_time')->join('user us', 'order.assignor=us.user_id', 'left')->join('order_times', 'order.order_id=order_times.order_id', 'left')->join('store st', 'us.store_id=st.store_id', 'left')->join('province p', 'order.province_id=p.province_id', 'left')->join('city c', 'order.city_id=c.city_id', 'left')->join('county y', 'order.county_id=y.county_id', 'left')->where(['order.order_id' => $data['order_id']])->find();
                    if ($li['dispatch_time'] > $month['first'] && ($OrderUserId['entry_type'] != 1 || $OrderUserId['hematopoiesis'] != 1 || ($OrderUserId['entry_user_id'] != $OrderUserId['assignor']))) {
                        db('dispatch_config_user', config('database.zong'))->where(['user_id' => $OrderUserId['assignor']])->update(['available_dispatch_quantity' => ['inc', 1]]);
                        $zhuan = db('dispatch_config_user', config('database.zong'))->where(['user_id' => $OrderUserId['assignor']])->value('available_dispatch_quantity');
                        \db('user_dispatch_log', config('database.zong'))->insertGetId(['order_id' => $data['order_id'], 'user_id' => $OrderUserId['assignor'], 'action_type' => 1, 'action_quantity' => 1, 'add_type' => 4, 'dispatch_quantity' => $zhuan, 'remark' => 'APP订单转派额度增加', 'create_time' => $time]);
                    }
                    if ($li['dispatch_time'] > $month['first'] && ($OrderUserId['entry_type'] == 1 && $OrderUserId['hematopoiesis'] == 1 && $OrderUserId['entry_user_id'] == $OrderUserId['assignor'])) {
                        db('dispatch_config_user', config('database.zong'))->where(['user_id' => $OrderUserId['assignor']])->update(['dispatch_quantity_total' => ['dec', 1]]);
                    }
                    
                    $s = $li['province'] . $li['city'] . $li['county'] . $li['addres'];
                    
                    db('remind')->insertGetId(['admin_id' => $transfer_record_confirm['user_id'], 'order_id' => $data['order_id'], 'time' => $time, 'stater' => 1, 'tai' => 1,]);
                    $content = "尊敬的{$li['username']}店长您好！客户:{$li['contacts']}，地址:{$s}，电话:{$li['telephone']}，订单：{$li['order_no']}来了，请尽快联系客户预约上门服务。如有任何问题都可致电4000-987-009,回T退订";
                    if (!empty($li['registrationId'])) {
                        $data = array('order_id' => $data['order_id'], 'content' => $content, 'type' => 6, 'user_id' => $transfer_record_confirm['user_id']);
                        $jpush->tui($content, $li['registrationId'], $data);
                    }
                    db('through')->where('order_ids', $data['order_id'])->update(['handle' => $time]);
                    db('user_dispatch_statistics')->insert(['order_id'=>$data['order_id'],'action_type'=>2,'create_time'=>$time,'action_quantity'=>'-1','user_id'=>$OrderUserId['assignor']]);
                    db('user_dispatch_statistics')->insert(['order_id'=>$data['order_id'],'action_type'=>1,'create_time'=>$time,'action_quantity'=>1,'user_id'=> $transfer_record_confirm['user_id']]);
                    \db('workbench_read')->where('order_id', $data['order_id'])->update(['have' => $time, 'already' => 0]);
                    \db('order_extend_info')->where('order_id', $data['order_id'])->update(['user_level' => $dispatch_config_user[$value], 'dispatch_level' => $dispatch_config_user['dispatch_level']]);
                    $order_times = db('order_times')->where('order_id', $data['order_id'])->find();
                    if ($order_times) {
                        db('order_times')->where('order_id', $data['order_id'])->update(['turn_time' => $time]);
                    }
                    
                }
                
            }
            db()->commit();
            sendOrder($data['order_id']);
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
            
        }
    }
}